<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Study Resource Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap');
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f7f9fb;
        }
        /* Custom scrollbar for better aesthetics */
        ::-webkit-scrollbar { width: 8px; }
        ::-webkit-scrollbar-track { background: #f1f1f1; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
        .resource-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .resource-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        .tag {
            cursor: pointer;
            transition: background-color 0.1s;
        }
        .tag:hover {
            background-color: #e0f2f1;
        }
        .modal-overlay {
            background-color: rgba(0, 0, 0, 0.6);
        }
    </style>
</head>
<body class="min-h-screen">

    <!-- Icon SVGs for easy use -->
    <script>
        const getIconSvg = (type, className = "w-6 h-6") => {
            let path = "";
            let color = "";
            switch (type) {
                case 'document':
                    path = '<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><path d="M14 2v6h6"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/>';
                    color = "text-indigo-500";
                    break;
                case 'audio':
                    path = '<path d="M3 10v4h2l3 3V7l-3 3H3z"/><path d="M16.14 8.13a4.95 4.95 0 0 1 0 7.74"/><path d="M19.78 5.57a9.4 9.4 0 0 1 0 12.86"/>';
                    color = "text-green-500";
                    break;
                case 'image':
                    path = '<rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>';
                    color = "text-red-500";
                    break;
                case 'archive':
                    path = '<rect width="20" height="5" x="2" y="3" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/>';
                    color = "text-yellow-600";
                    break;
                default:
                    path = '<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>';
                    color = "text-gray-500";
            }
            return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="${className} ${color}">${path}</svg>`;
        };
    </script>

    <!-- Main Application Container -->
    <div class="p-4 sm:p-8">

        <!-- Header -->
        <header class="mb-8 flex flex-col sm:flex-row justify-between items-start sm:items-center">
            <h1 class="text-3xl font-bold text-gray-800 mb-2 sm:mb-0">
                Study Resource Library
            </h1>
            <button id="open-upload-modal" class="flex items-center space-x-2 bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out transform hover:scale-[1.02]">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
                <span>Upload New Resource</span>
            </button>
        </header>

        <!-- Search and Filter Bar -->
        <div class="bg-white p-6 rounded-xl shadow-lg mb-8 border border-gray-100">
            <h2 class="text-xl font-semibold text-gray-700 mb-4">Filter Resources</h2>
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                
                <!-- Search Input -->
                <div>
                    <label for="search" class="block text-sm font-medium text-gray-700 mb-1">Search Title / Tag</label>
                    <input type="text" id="search" placeholder="e.g., React, SQL, Midterm" class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150">
                </div>

                <!-- Category Filter -->
                <div>
                    <label for="category-filter" class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                    <select id="category-filter" class="w-full border border-gray-300 rounded-lg p-2 bg-white focus:ring-indigo-500 focus:border-indigo-500 transition duration-150">
                        <option value="">All Categories</option>
                    </select>
                </div>

                <!-- Course Filter -->
                <div>
                    <label for="course-filter" class="block text-sm font-medium text-gray-700 mb-1">Course</label>
                    <select id="course-filter" class="w-full border border-gray-300 rounded-lg p-2 bg-white focus:ring-indigo-500 focus:border-indigo-500 transition duration-150">
                        <option value="">All Courses</option>
                    </select>
                </div>

                <!-- Type Filter -->
                <div>
                    <label for="type-filter" class="block text-sm font-medium text-gray-700 mb-1">Resource Type</label>
                    <select id="type-filter" class="w-full border border-gray-300 rounded-lg p-2 bg-white focus:ring-indigo-500 focus:border-indigo-500 transition duration-150">
                        <option value="">All Types</option>
                        <option value="document">Document</option>
                        <option value="audio">Audio</option>
                        <option value="image">Image</option>
                        <option value="archive">Archive</option>
                        <option value="other">Other</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Resource Grid -->
        <div id="resource-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            <!-- Resources will be injected here by JavaScript -->
        </div>

        <!-- No Results Message -->
        <div id="no-results" class="text-center py-12 hidden">
            <p class="text-xl text-gray-500">No resources matched your current filter criteria. Try adjusting your search terms.</p>
        </div>

    </div>

    <!-- Upload Resource Modal (Hidden by default) -->
    <div id="upload-modal" class="fixed inset-0 z-50 overflow-y-auto hidden">
        <div class="modal-overlay absolute w-full h-full"></div>
        <div class="flex items-center justify-center min-h-screen p-4 sm:p-0">
            <div class="bg-white w-full max-w-2xl rounded-xl shadow-2xl z-50 overflow-hidden transform transition-all">
                
                <!-- Modal Header -->
                <div class="p-6 border-b border-gray-200 flex justify-between items-center">
                    <h3 class="text-2xl font-bold text-gray-800">Upload New Study Resource</h3>
                    <button id="close-upload-modal" class="text-gray-400 hover:text-gray-600 transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
                    </button>
                </div>

                <!-- Modal Body (Form) -->
                <form id="upload-form" class="p-6 space-y-4">
                    
                    <div>
                        <label for="upload-title" class="block text-sm font-medium text-gray-700 mb-1">Title <span class="text-red-500">*</span></label>
                        <input type="text" id="upload-title" required class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500">
                    </div>

                    <div>
                        <label for="upload-description" class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                        <textarea id="upload-description" rows="3" class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500"></textarea>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label for="upload-course" class="block text-sm font-medium text-gray-700 mb-1">Associated Course</label>
                            <select id="upload-course" class="w-full border border-gray-300 rounded-lg p-2 bg-white focus:ring-indigo-500 focus:border-indigo-500">
                                <option value="">(Optional)</option>
                            </select>
                        </div>
                        <div>
                            <label for="upload-category" class="block text-sm font-medium text-gray-700 mb-1">Category <span class="text-red-500">*</span></label>
                            <input type="text" id="upload-category" required class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500" placeholder="e.g., Notes, Solutions, Lectures">
                        </div>
                    </div>

                    <div>
                        <label for="upload-tags" class="block text-sm font-medium text-gray-700 mb-1">Tags (Comma-separated)</label>
                        <input type="text" id="upload-tags" class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500" placeholder="e.g., Python, Data Structures, Exam Review">
                    </div>

                    <div>
                        <label for="upload-file" class="block text-sm font-medium text-gray-700 mb-1">Resource File <span class="text-red-500">*</span></label>
                        <input type="file" id="upload-file" required class="w-full file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100 transition duration-150">
                    </div>

                    <div class="flex items-center pt-2">
                        <input id="upload-shared" type="checkbox" class="h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500">
                        <label for="upload-shared" class="ml-2 block text-sm text-gray-900">Share with other instructors/users?</label>
                    </div>


                    <!-- Modal Footer (Submit) -->
                    <div class="pt-4 flex justify-end space-x-3">
                        <button type="button" id="cancel-upload" class="py-2 px-4 rounded-lg text-gray-600 hover:bg-gray-100 transition duration-150">Cancel</button>
                        <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out">
                            Submit Resource
                        </button>
                    </div>
                </form>

            </div>
        </div>
    </div>


    <script>
        // --- 1. SIMULATED DATA ---
        const simulatedResources = [
            { id: 1, title: 'Introduction to React Hooks', description: 'A comprehensive guide to useState and useEffect, focusing on practical implementation.', type: 'document', category: 'Web Development', tags: ['React', 'Frontend', 'JS'], courseId: 'CS101', date: '2025-10-20', author: 'Dr. Jane Doe' },
            { id: 2, title: 'Database Normalization Cheatsheet', description: 'Quick reference for 1NF, 2NF, and 3NF with examples.', type: 'document', category: 'Databases', tags: ['SQL', 'Design'], courseId: 'CS205', date: '2025-10-18', author: 'Dr. Jane Doe' },
            { id: 3, title: 'Quantum Physics Lecture 5', description: 'Audio recording of the lecture on Schrödinger\'s equation and its applications.', type: 'audio', category: 'Physics', tags: ['Quantum', 'Audio', 'Theory'], courseId: 'PHY301', date: '2025-10-15', author: 'Prof. Alex Smith' },
            { id: 4, title: 'Midterm Exam Solutions (CS101)', description: 'PDF of solved problems for CS101 midterms, covering modules 1-3.', type: 'document', category: 'Exams', tags: ['Practice', 'Midterm'], courseId: 'CS101', date: '2025-10-10', author: 'Dr. Jane Doe' },
            { id: 5, title: 'Course Project Templates (ZIP)', description: 'Starter files and directory structure for the final course project.', type: 'archive', category: 'Projects', tags: ['Template', 'Files', 'Code'], courseId: 'CS205', date: '2025-10-05', author: 'Prof. Alex Smith' },
            { id: 6, title: 'Linear Algebra Review Slides', description: 'Presentation slides covering eigenvalues and eigenvectors.', type: 'document', category: 'Mathematics', tags: ['Math', 'Algebra', 'Slides'], courseId: 'MAT210', date: '2025-10-01', author: 'Dr. Jane Doe' },
            { id: 7, title: 'CSS Grid Layout Explained', description: 'A simple image diagram explaining common CSS Grid properties.', type: 'image', category: 'Web Development', tags: ['CSS', 'Frontend'], courseId: 'CS101', date: '2025-09-28', author: 'Dr. Jane Doe' },
        ];

        // --- 2. UTILITY FUNCTIONS ---

        /**
         * Generates the HTML for a single resource card.
         * @param {Object} resource 
         * @returns {string} HTML string
         */
        function createResourceCard(resource) {
            const date = new Date(resource.date).toLocaleDateString();
            
            const tagsHtml = resource.tags.map(tag => 
                `<span class="tag bg-teal-50 text-teal-700 text-xs font-medium px-2 py-0.5 rounded-full hover:bg-teal-100 transition duration-150" data-tag="${tag}">#${tag}</span>`
            ).join('');

            return `
                <div class="resource-card bg-white rounded-xl p-6 shadow-md border border-gray-100 flex flex-col justify-between">
                    <div>
                        <div class="flex items-center space-x-3 mb-3">
                            ${getIconSvg(resource.type, "w-8 h-8 flex-shrink-0")}
                            <div>
                                <h3 class="text-lg font-bold text-gray-900 line-clamp-2">${resource.title}</h3>
                                <p class="text-sm text-indigo-600 font-semibold">${resource.courseId}</p>
                            </div>
                        </div>
                        
                        <p class="text-sm text-gray-500 mb-3 line-clamp-3">${resource.description}</p>
                        
                        <div class="flex flex-wrap gap-2 mb-4">
                            ${tagsHtml}
                        </div>
                    </div>
                    
                    <div class="pt-3 border-t border-gray-100 flex justify-between items-center text-xs text-gray-400">
                        <span class="truncate pr-2" title="${resource.author}">${resource.author}</span>
                        <span>${date}</span>
                    </div>

                    <a href="#" class="mt-4 block text-center bg-gray-100 text-gray-700 hover:bg-indigo-100 hover:text-indigo-600 font-medium py-2 rounded-lg transition duration-150 ease-in-out">
                        View/Download
                    </a>
                </div>
            `;
        }


        // --- 3. FILTERING AND RENDERING LOGIC ---

        const resourceGrid = document.getElementById('resource-grid');
        const noResults = document.getElementById('no-results');
        const searchInput = document.getElementById('search');
        const categoryFilter = document.getElementById('category-filter');
        const courseFilter = document.getElementById('course-filter');
        const typeFilter = document.getElementById('type-filter');

        let currentFilters = {
            search: '',
            category: '',
            course: '',
            type: ''
        };

        /**
         * Renders the filtered list of resources to the DOM.
         */
        function renderResources() {
            const { search, category, course, type } = currentFilters;
            const searchTerm = search.toLowerCase();

            const filteredResources = simulatedResources.filter(resource => {
                const matchesSearch = resource.title.toLowerCase().includes(searchTerm) || 
                                      resource.tags.some(tag => tag.toLowerCase().includes(searchTerm));
                
                const matchesCategory = !category || resource.category === category;
                const matchesCourse = !course || resource.courseId === course;
                const matchesType = !type || resource.type === type;

                return matchesSearch && matchesCategory && matchesCourse && matchesType;
            });

            resourceGrid.innerHTML = filteredResources.map(createResourceCard).join('');

            // Toggle No Results message
            if (filteredResources.length === 0) {
                noResults.classList.remove('hidden');
                resourceGrid.classList.add('hidden');
            } else {
                noResults.classList.add('hidden');
                resourceGrid.classList.remove('hidden');
            }
        }

        /**
         * Populates the filter dropdowns with unique values from the simulated data.
         */
        function populateFilters() {
            const uniqueCategories = [...new Set(simulatedResources.map(r => r.category))].sort();
            const uniqueCourses = [...new Set(simulatedResources.map(r => r.courseId))].sort();

            const createOptions = (values) => values.map(v => `<option value="${v}">${v}</option>`).join('');

            categoryFilter.insertAdjacentHTML('beforeend', createOptions(uniqueCategories));
            courseFilter.insertAdjacentHTML('beforeend', createOptions(uniqueCourses));

            // Also populate the modal course dropdown
            const uploadCourseSelect = document.getElementById('upload-course');
            uploadCourseSelect.insertAdjacentHTML('beforeend', createOptions(uniqueCourses));
        }

        /**
         * Attaches event listeners for filtering inputs.
         */
        function setupFilterListeners() {
            searchInput.addEventListener('input', (e) => {
                currentFilters.search = e.target.value;
                renderResources();
            });

            [categoryFilter, courseFilter, typeFilter].forEach(filter => {
                filter.addEventListener('change', (e) => {
                    currentFilters[e.target.id.split('-')[0]] = e.target.value;
                    renderResources();
                });
            });

            // Listen for tag clicks on the cards
            resourceGrid.addEventListener('click', (e) => {
                const tagSpan = e.target.closest('.tag');
                if (tagSpan) {
                    const tag = tagSpan.dataset.tag;
                    searchInput.value = tag;
                    currentFilters.search = tag;
                    renderResources();
                }
            });
        }


        // --- 4. MODAL LOGIC ---

        const uploadModal = document.getElementById('upload-modal');
        const openModalBtn = document.getElementById('open-upload-modal');
        const closeModalBtn = document.getElementById('close-upload-modal');
        const cancelUploadBtn = document.getElementById('cancel-upload');
        const uploadForm = document.getElementById('upload-form');

        openModalBtn.addEventListener('click', () => {
            uploadModal.classList.remove('hidden');
        });

        const hideModal = () => {
            uploadModal.classList.add('hidden');
            uploadForm.reset(); // Clear the form on close
        };

        [closeModalBtn, cancelUploadBtn].forEach(btn => {
            btn.addEventListener('click', hideModal);
        });

        // Simple form submission handler (simulated)
        uploadForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            const title = document.getElementById('upload-title').value;
            const fileInput = document.getElementById('upload-file');
            
            if (fileInput.files.length === 0) {
                // In a real app, this would be an inline error message
                console.error("Please select a file.");
                return;
            }

            console.log(`Simulating upload for: ${title}`);
            
            // In a real application, you would handle the file upload and database insertion here.
            // For this redesign, we just hide the modal and provide feedback.
            alertUserMessage('success', `Resource "${title}" uploaded successfully! (Simulated)`);
            hideModal();
        });


        // --- 5. INITIALIZATION ---

        function alertUserMessage(type, message) {
            // A simple placeholder for showing messages instead of alert()
            const existingAlert = document.getElementById('app-alert');
            if (existingAlert) existingAlert.remove();
            
            const color = type === 'success' ? 'bg-green-100 text-green-800 border-green-400' : 'bg-red-100 text-red-800 border-red-400';
            
            const alertHtml = `
                <div id="app-alert" class="fixed top-4 right-4 z-50 p-4 rounded-lg shadow-xl border ${color} transition duration-300 transform translate-y-0" role="alert">
                    <p class="font-medium">${message}</p>
                </div>
            `;
            document.body.insertAdjacentHTML('beforeend', alertHtml);

            // Automatically remove after 5 seconds
            setTimeout(() => {
                const currentAlert = document.getElementById('app-alert');
                if (currentAlert) currentAlert.remove();
            }, 5000);
        }

        window.onload = function() {
            populateFilters();
            setupFilterListeners();
            renderResources(); // Initial render
        };
    </script>
</body>
</html>